package com.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.MimeMessage;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * @author zz
 * @version 1.0
 * @Description
 */
@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username:zwt20171027@163.com}")
    private String from;
    @Autowired
    private TemplateEngine templateEngine;
    @RequestMapping("send")
    public String send(String code) {
        try {
            MimeMessage mimeMessage= javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo("2285654111@qq.com");
            helper.setSubject("测试邮件");
            Context context = new Context();
            context.setVariable("code", code);
            helper.setText(templateEngine.process("emailTemplate", context), true);
            javaMailSender.send(mimeMessage);
//            helper.setText("<html><body><h1>" + code + "</h1></body></html>", true);
//            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//            simpleMailMessage.setFrom(from);
//            simpleMailMessage.setTo("2285654111@qq.com");
//            simpleMailMessage.setSubject("测试邮件");
//            simpleMailMessage.setText(from + "测试邮件");
//            javaMailSender.send(simpleMailMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "发送成功";
    }
}
